package cn.tedu.egweibo4.controller;

import cn.tedu.egweibo4.base.response.JsonResult;
import cn.tedu.egweibo4.base.response.StatusCode;
import cn.tedu.egweibo4.mapper.UserMapper;
import cn.tedu.egweibo4.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo4.pojo.dto.UserRegDTO;
import cn.tedu.egweibo4.pojo.entity.User;
import cn.tedu.egweibo4.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RestController
@Api(tags = "01.用户模块")
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @ApiOperation(value = "注册功能功能")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO = {}", userRegDTO);
        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        log.debug("userVO = {}", userVO);
        if (userVO!=null){
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();

    }

    @PostMapping("login")
    @ApiOperation(value = "登录功能功能")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession httpSession){
        log.debug("userLoginDTO = {}", userLoginDTO);
        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userVO.getPassword().equals(userLoginDTO.getPassword())){
            httpSession.setAttribute("user",userVO);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }

    @GetMapping("currentUser")
    @ApiOperation(value = "获取当前用户功能")
    public JsonResult currentUser(@ApiIgnore HttpSession httpSession){
        UserVO userVO = (UserVO) httpSession.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @GetMapping("logout")
    @ApiOperation(value = "退出登录功能")
    public void logout(@ApiIgnore HttpSession httpSession){
        httpSession.removeAttribute("user");
    }

}
